package jee.boot.module.act.service;

import jee.boot.common.basic.CrudService;
import jee.boot.common.basic.ServiceException;
import jee.boot.common.standard.AuthorityHandler;
import jee.boot.common.utils.StringUtils;
import jee.boot.entity.activiti.ActExecution;
import jee.boot.entity.activiti.ActTask;
import jee.boot.entity.auth.User;
import jee.boot.module.act.dao.ActExecutionDao;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ActExecutionService extends CrudService<ActExecutionDao, ActExecution> {
    @Autowired
    private IdentityService identityService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private AuthorityHandler authorityHandler;

    public ActExecution start(ActExecution entity) {
        User user = authorityHandler.getCurrentUser();
        if (user == null) {
            throw new ServiceException(1409);
        }
        if (entity.getProcDef() == null || StringUtils.isBlank(entity.getProcDef().getKey())) {
            throw new ServiceException(1412);
        }
        // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
        identityService.setAuthenticatedUserId(authorityHandler.getUserId());
        // 启动流程
        ProcessInstance procIns = runtimeService.startProcessInstanceByKey(entity.getProcDef().getKey(), entity.getBusinessKey(), entity.getVariable().toMap());
        entity.setId(procIns.getId());
        return entity;
    }
}
